package com.buildings.activity;

import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.buildings.R;
import com.buildings.adapter.FileListAdapter;
import com.buildings.base.BaseActivity;
import com.buildings.base.BaseApplication;
import com.buildings.bean.FileSelectEntity;
import com.buildings.bean.RelationTaskDbBean;
import com.buildings.event.AboutTaskEvent;
import com.buildings.view.AboutTaskFragmentDialog;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class ReadFileActivity extends BaseActivity {
    static final String path = "/storage/emulated/0/Download/WeiXin";
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.tv_right_text)
    TextView tvightText;
    @BindView(R.id.ll_btn)
    LinearLayout llBtn;
    private List<FileSelectEntity> files = new ArrayList<>();
    private FileListAdapter fileListAdapter;
    private boolean isEdit = false;
    //需要绑定的文件数据集
    private List<File> bindFiles = new ArrayList<>();

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_read_file);
        ButterKnife.bind(this);
        EventBus.getDefault().register(this);
        initView();
        refashData(path);
    }

    private void initView() {
        tvTitle.setText("文件列表");
        tvightText.setText("多选");
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        recyclerView.addItemDecoration(new DividerItemDecoration(this, LinearLayoutManager.VERTICAL));
        fileListAdapter = new FileListAdapter(this, files);
        recyclerView.setAdapter(fileListAdapter);
        fileListAdapter.setOnItemClickListener(new FileListAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(int position) {
                if (isEdit){
                    return;
                }
                //关联任务
                bindFiles.clear();
                bindFiles.add(files.get(position).getFile());
                AboutTaskFragmentDialog.newInstance().show(getSupportFragmentManager(), "");
            }

            @Override
            public void onCheck(int position) {
                files.get(position).setSelect(!files.get(position).isSelect());
                fileListAdapter.notifyDataSetChanged();
            }

            @Override
            public void onDelete(int position) {
                //删除本地内存下的文件
                files.get(position).getFile().delete();
                files.remove(position);
                fileListAdapter.notifyDataSetChanged();
            }
        });
        refreshLayout.setOnRefreshListener(refreshlayout -> {
            refashData(path);
            fileListAdapter.notifyDataSetChanged();
        });
        refreshLayout.setEnableLoadmore(false);
    }

    @OnClick({R.id.iv_back, R.id.tv_right_text, R.id.btn_delete, R.id.btn_about_task})
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.tv_right_text:
                isEdit = !isEdit;
                if (isEdit) {
                    llBtn.setVisibility(View.VISIBLE);
                } else {
                    llBtn.setVisibility(View.GONE);
                }
                fileListAdapter.setIsEdit(isEdit);
                break;
            case R.id.btn_delete:
                Iterator<FileSelectEntity> iterator = files.iterator();
                while (iterator.hasNext()) {
                    FileSelectEntity fileSelectEntity = iterator.next();
                    if (fileSelectEntity.isSelect()) {
                        iterator.remove();
                        fileSelectEntity.getFile().delete();
                    }
                }
                refashData(path);
                fileListAdapter.notifyDataSetChanged();
                break;
            case R.id.btn_about_task:
                bindFiles.clear();
                for (FileSelectEntity fileSelectEntity : files) {
                    if (fileSelectEntity.isSelect())
                        bindFiles.add(fileSelectEntity.getFile());
                }
                AboutTaskFragmentDialog.newInstance().show(getSupportFragmentManager(), "");
                break;
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void receiveMeage(AboutTaskEvent json) {
        String projectId = json.getProjectId();
        String taskId = json.getTableId();
        // 任务id 项目id  路径名
        for (File file : bindFiles){
            RelationTaskDbBean relationTaskDbBean = new RelationTaskDbBean();
            relationTaskDbBean.setProjectId(projectId);
            relationTaskDbBean.setTaskId(taskId);
            relationTaskDbBean.setFilePath(file.getPath());
            BaseApplication.getInstance().getDaoSession().insert(relationTaskDbBean);
        }
    }


    // 获取当前目录下所有的mp4 MOV文件
    private void refashData(String fileDir) {
        files.clear();
        List<File> pathList = new ArrayList<>();
        File file = new File(fileDir);
        if (!file.exists()) {
            Toast("暂无数据");
            return;
        }
        File[] subFile = file.listFiles();
        for (int iFileLength = 0; iFileLength < subFile.length; iFileLength++) {
            String filename = subFile[iFileLength].getName();
            // 判断是否为文件夹
            FileSelectEntity fileSelectEntity = new FileSelectEntity();
            if (filename.trim().toLowerCase().endsWith(".kml")) {
                fileSelectEntity.setFile(subFile[iFileLength]);
                files.add(fileSelectEntity);
            } else if (filename.trim().toLowerCase().endsWith(".kmz")) {
                fileSelectEntity.setFile(subFile[iFileLength]);
                files.add(fileSelectEntity);
            } else if (filename.trim().toLowerCase().endsWith(".json")) {
                fileSelectEntity.setFile(subFile[iFileLength]);
                files.add(fileSelectEntity);
            }
            pathList.add(subFile[iFileLength]);
        }
        refreshLayout.finishRefresh();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
